<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>散客买茶第一步</title>
<jsp:include page="/header.jsp"></jsp:include>
<link href="${basePath }/css/ui.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	$(function() {
		
		$(document).keydown(function(event){
			switch(event.keyCode) {
				case 13:{
					var flag = $("#common_div").css("display");
					if(flag=="block") scan();
				}
			}
		});
		
		/* var s = "20140615017001&20140615017002";
		alert(s.replace("20140615017001", "")); */
		loadCookie();
		$("#temp_div").hide();
		
		loadProductDialog();
		
		/* $("#find_product_text").autocomplete({
			source:"${basePath}/scat/find_product.htm",
			select:function(event, ui) {
				$("#vague_product_info").val(ui.item.id);
				$("#unit-div").load("${basePath}/scat/find_unit.htm?id="+ui.item.id);
			}
		}); */
		
		$("#find-product-button").click(function() {
			$("#product-table").load("${basePath}/scat/findProduct.htm?info="+$("#find_product_text").val());
		})
		
	});
	
	function selectProduct(id, name) {
		$("input[name*='temp-unit']").attr("disabled", "disabled");
		$("input[name*='temp-unit']").removeAttr("checked");
		$("input[name='"+id+"-temp-unit']").removeAttr("disabled");
		$("#vague_product_info").val(id);
		$("#find_product_text").val(name);
	}
	
	function selectUnit(unit) {
		$("#vague_product_unit").val(unit);
	}
	
	function loadProductDialog() {
		$("#find_product_dialog").dialog({
			title:"商品信息",
			autoOpen: false,
			height: 500,
			width: 600,
			modal: true,
			buttons:[{
				text:"确定",
				click:function() {
					$("#product_info").val($("#find_product_text").val());
					$(this).dialog("close");
				}
			},{
				text:"取消",
				click:function() {
					$(this).dialog("close");
				}
			}]
		});
	}
	
	function loadCookie() {
		var codes_str = $.cookie("shop_cart");
		if(codes_str==undefined||codes_str.replaceAll("&", "")=="") return;
		else {
			$.ajax({
				url:"${basePath}/scat/loadCookie.htm",
				type:"post",
				data:{codes:codes_str},
				dataType:"json",
				success:function(data) {
					$.each(data, function(i, product){
						jsAddProductTr(product);
					});	
				}
			});
		}
	}
	
	function jsAddProductTr(product) {
		var tr = $("table").find("tr");
		var index = 0;
		if(tr!=null) index = Number(tr.last().find("td").first().text());
		var html = "<tr id=\""+product.code+"\"><td name='index'>"+(index+1)+"</td><td name='name'>"+product.name+"</td>"+
			"<td name='code'>"+product.code+"</td><td name='productionyear'>"+product.productionyear+"</td>"+
			"<td name='batch'>"+product.batch+"</td><td name='type'>"+product.aunit+"</td>"+
			"<td name='price'>"+product.price+"</td><td name='discount'><select onchange='changePrice(this);'>";
		var options = "<option value='1'>无</option>";
		$.each(product.discounts, function(i, n) {
			options += "<option value='"+n.value+"'";
			if(n.value==product.discount) options += "selected='selected'";
			options += ">"+n.value+"</option>";
		});
		var discount = product.discount;
		discount = discount==null?1:Number(discount);
		var orgPrice = Number(product.price);
		html += options+"</select></td><td name='price2'>"+discount.mul(orgPrice)+
			"</td><td><a href='javascript:;' onclick='del(\""+product.code+
			"\");'>删除</a><input type='hidden' name='product_id' value='"+product.commodity_id+"'>"+
			"<input type='hidden' name='unit_type' value='"+product.unit_type+"'></tr>";
		$("table").append(html);
		
		var before = Number($("#sum_price").text());
		$("#sum_price").text(before+product.price);
	}
	
	//扫描二维码
	function scan() {
		var code = $("#code").val();
		if(code==""||code==null) {
			$.jqalert("请扫描二维码！！", "提示");
		} else {
			$.ajax({
				url:"${basePath}/scat/scan.htm?code="+$("#code").val(),
				dataType:"json",
				success:function(data) {
					if(!data.isSuccess) {
						$.jqalert(data.msg, "提示");
					} else {
						jsAddProductTr(data.json.product);
						$("#code").val("");
					}
				}
			});
		}
	}
	
	//删除一行
	function del(code) {
		var index = Number($("#"+code).find("td").first().text());
		var trs = $("table").find("tr:gt("+index+")");
		$.each(trs, function(i, n){
			var td = $(n).find("td").first();
			td.text(Number(td.text())-1);
		});
		$("#"+code).remove();
		
		var codes = $.cookie("shop_cart");
		codes = codes.replaceAll(code, "");
		codes = codes.replaceAll("&&", "&");
		$.cookie("shop_cart", codes, {path:"/"});
		
		var tempscookie = $.cookie("temps");
		if(tempscookie!=undefined&&tempscookie!='') {
			var temps = eval("("+tempscookie+")");
			$.each(temps, function(i, n){
				if(n.code==code) {
					temps.splice(i, 1);
				}
			});
			$.cookie("temps", JSON.stringify(temps), {path:"/"});
		}
		resetSum();
	}
	
	//删除全部
	function delAll() {
		var tr = $("table").find("tr").first();
		$("table").empty();
		$("table").append(tr);
		
		$.removeCookie("shop_cart", {path:"/"});
		$.removeCookie("temps", {path:"/"});
		
		resetSum();
	}
	
	//确认购买
	function confirm() {
		if(Number($("#sum_price").text())==0) {
			alert("请选择要购买的商品！！");return;
		}
		var products = new Array();
		$.each($(".table_list>tbody>tr:gt(0)"), function(i, n){
			var product = {};
			$.each($(n).children(), function(i, n){
				var value = "";
				if(i==7) value = $(n).children().first().find('option:selected').text();
				else value = $(n).text();
				console.info("product."+$(n).attr("name")+"=\""+value+"\"");
				eval("product."+$(n).attr("name")+"=\""+value+"\"");
			});
			//product.id = $(n).find("input[type='hidden']").val();
			product.is_save = 0;
			product.product_id = $(n).find("input[name='product_id']").val();
			product.unit_type = $(n).find("input[name='unit_type']").val();
			products.push(product);
		});
		$.cookie("products", JSON.stringify(products), {path:"/"});
		window.location = "${basePath}/scat/next.htm";
	}
	
	//临时二维码
	function temp() {
		$("#temp_div").find("input").val("");
		$("#temp_div").show();
		$("#common_div").hide();
	}
	
	//确定，切回扫描商品二维码
	function sure() {
		var temp_code = $("#temp_code").val();
		var product_id = $("#vague_product_info").val();
		var unit = $("#vague_product_unit").val();
		if(temp_code==""||temp_code==null) $.jqalert("请输入临时二维码", "提示");
		else if(product_id==""||product_id==null) $.jqalert("请选择商品", "提示");
		else {
			$.ajax({
				url:"${basePath}/scat/temp_scan.htm?id="+product_id+"&temp="+temp_code+"&unit="+unit,
				dataType:"json",
				success:function(data) {
					if(!data.isSuccess) {
						$.jqalert(data.msg, "提示");
					} else {
						jsAddProductTr(data.json.product);
						var temps = $.cookie("temps");
						var array = new Array();
						if(temps!=undefined) array = eval("("+temps+")");;
						var product = {};
						product.type_display = data.json.product.type_display;
						product.code = data.json.product.code;
						product.commodity_id = data.json.product.commodity_id;
						array.push(product);
						$.cookie("temps", JSON.stringify(array), {path:"/"});
					}
				}
			});
		}
	}
	
	function change() {
		
		$("#temp_div").hide();
		$("#common_div").find("input").val("");
		$("#common_div").show();
	}
	
	//清除cookie
	function removeCookie() {
		$.removeCookie("shop_cart", {path:"/"});
		alert("已经清除！");
	}
	
	//显示cookie
	function viewCookie() {
		alert($.cookie("shop_cart"));
	}
	
	//查找商品
	function find() {
		$("#find_product_dialog").find("input[type='text']").val("");
		$("#find_product_dialog").dialog("open");
	}
	
	//重置总计金额
	function resetSum() {
		var sum = 0;
		$.each($("tr:gt(0)"), function(i, n){
			var money = Number($(n).find("td").eq(8).text());
			sum += money;
		});
		$("#sum_price").text(sum);
	}
	
	//动态变更折后价
	function changePrice(select) {
		var discount = Number($(select).val());
		var orgPrice = Number($(select).parent().prev().text());
		$(select).parent().next().text(orgPrice.mul(discount));
		
		var code = $(select).parent().parent().attr("id");
		
		var back_discounts = $.cookie("back_discounts");
		if(back_discounts==undefined) back_discounts = new Array();
		else back_discounts = eval("("+back_discounts+")");
		var flag = true;
		$.each(back_discounts, function(i, n){
			if(n.key==code) {
				n.value = discount;
				flag = false;
			}
		});
		if(flag) {
			var back_discount = {};
			back_discount.key = code;
			back_discount.value = discount;
			back_discounts.push(back_discount);
		}
		$.cookie("back_discounts", JSON.stringify(back_discounts), {path:"/"});
		resetSum();
	}
</script>
</head>
<body>
    <div class="main">
        <div class="cont">
            <h2 class="title">散客买茶：</h2>
            <div class="ui">
                <div class="label_box" id="common_div">
                    <span class="sel_label fl">扫描商品：</span>
                    <input type="text" id="code" class="text_input fl">
                    <a href="javascript:;" class="" onclick="temp();">使用临时二维码</a>
                </div>
                <div class="label_box" id="temp_div">
                    <span class="sel_label fl">临时二维码：</span>
                    <input type="text" id="temp_code" class="text_input fl">
                    <span class="sel_label fl">查找商品：</span>
                    <input type="text" id="product_info" class="text_input fl">
                    <input type="hidden" id="vague_product_info">
                    <input type="hidden" id="vague_product_unit">
                    <a href="javascript:;" class="" onclick="find();">查找</a>
                    <a href="javascript:;" class="" onclick="sure();">确定</a>
                    <a href="javascript:;" onclick="change();">使用二维码</a>
                </div>
            </div>
            <h2 class="title"> 查询结果：</h2>
            <div class="ui">
                <table class="table_list">
                    <tr class="">
                      <th class="">序号</th>
                      <th>品名</th>
                      <th class="">二维码</th>
                      <th class="">年份</th>
                      <th class="">批次</th>
                      <th class="">类型</th>
                      <th>价格(元)</th>
                      <th class="">折扣</th>
                      <th class="">折后价</th>
                      <th class="">删除</th>
                    </tr>
                </table>
                <span class="sel_label fr">商品总金额：<span id="sum_price">0</span>元</span>
            </div>
            <div class="text_c">
	        	<a href="javascript:;" class="yellow_btn btn" onclick="confirm();">确认购买</a>
	        	&nbsp;&nbsp;
	        	<a href="javascript:;" onclick="delAll();">全部商品清空</a>
	        	<!-- &nbsp;&nbsp;
	        	<a href="javascript:;" onclick="viewCookie();">显示cookie</a> -->
	        </div>
            
        </div>
    </div>
    
    <div id="find_product_dialog">
	年份-商品：
	<input type="text" id="find_product_text">&emsp;<input type="button" value="查询" id="find-product-button">
	<br><br>
	<div id="unit-div">
	<!-- <input type="radio" name="temp_unit" value="1" checked="checked">整装&nbsp;
	<input type="radio" name="temp_unit" value="2">散装&nbsp;
	<input type="radio" name="temp_unit" value="3">筒装 -->
	</div>
	<table id="product-table">
	</table>
    </div>
</body>
</html>